/*
 * RequestHandler.java
 * This class gets either HTML page url or data inside HTML page for particular request.
 */

/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  guireportgenerator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Vector;

import query.view.Query;


import database.RecordSearch;
import dbmanager.DBManager;
import dbmanager.GetIdName;

import utility.CapitalChar;
import utility.Input;

public class RequestHandler
{
	GetIdName get;// GetIdName object for getting master id or name
	File file;	
	ResultSet rs;	
	String master, username, page,masterID,pageID, pagetype, process,report;
	Hashtable<Object, Object> conditionhash,datahash;
	/**
	 * Parametarized contructor with a single arg of database object
	 * @param db preinitialized database object 
	 */
	public RequestHandler()
	{
		this.get = new GetIdName();
	}
	
	/**
	 * This method sets the requested html page 
	 * @param page HTML page
	 */
	public void setRequestPage(String page)
	{
		this.page = page;
		
		try
		{
			this.pageID = get.getId(this.page);
		}
		catch (Exception e) {
			this.pageID = null;
		}
	}
	
	/**
	 * This method sets the master for which the page is been set
	 * @param master master object
	 */
	public void setMaster(String master)
	{
		this.master = master;
		
		try
		{
			this.masterID = get.getId(this.master);
		}
		catch (Exception e) {
			this.masterID = null;
		}
	}
	
	/**
	 * This method sets username
	 * @param username username
	 */
	public void setUsername(String username)
	{
		this.username = username;
	}
	
	/**
	 * This method checks whether requested page should be get using url or content of 
	 * page should be read.
	 *   
	 * @param username Username
	 * @param page The page which has to be fetched.
	 * @param master The master for which this page has been defined for that user.
	 * @return It returns a 'true' if its an url and 'false' either.
	 */
	public boolean isUrl()
	{
		get = new GetIdName();
		boolean result = false;
		Hashtable<Object, Object> condition = new Hashtable<Object, Object>();
		RecordSearch rec = new RecordSearch();
		String objectID = null;
		
		try
		{
			pagetype = null;
			
			if(this.pageID != null)
			{
				condition.put("mid",this.pageID);	
				condition.put("pid",get.getId("pagetype"));
				condition.put("td", "null");
				rec.setConditionMap(condition);
				rs = rec.getResultSet();
				
				while(rs.next())
				{
					pagetype = get.getItem(rs.getString("PV"));
					if(pagetype.equalsIgnoreCase("no$"))
						pagetype = rs.getString("VT");
				}
				rs.close();			
			}
						
			
			if(pagetype == null || pagetype.equalsIgnoreCase("static"))
			{
				result = true;
			}
			else if(pagetype != null || pagetype.equalsIgnoreCase("dynamic"))
			{
				result = false;
			}
			
			return result;
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			return true;
		}
	}
	
	/**
	 * This method generates HTML using master properties
	 * @return HTML content under page object
	 */
	public String getHtml()
	{
		WebReportGenerator web = null;
		
		// if pagetype is dynamic then it will generate html page 
		if (!pagetype.equalsIgnoreCase("link")) 
		{
			web = new WebReportGenerator(this.pageID, datahash,".html");
		}
		//if pagetype is link user will be redirected to a page return by report defined in the page object
		else
		{
			report = this.getReport(report, conditionhash);
			//report = "item_view";
			System.out.println("The report is "+report);
			this.page = report;
			web = new WebReportGenerator(get.getId(report), datahash,".html");
		}
		
		return web.getData();
	}
	
	public String getPage()
	{
		return this.page;
	}
	
	public void setRport(String report)
	{
		this.report = report;
	}
	
	/**
	 * This method gets HTML page name from defined report
	 * @param report Report name
	 * @param hash Condition values for report
	 * @return name of HTML page
	 */	
	public String getReport(String report, Hashtable<Object, Object> hash)
	{
		String result = null;
		try 
		{
			Vector<Object> condition =new Vector<Object>();
			condition.add(hash);
			Query query =new Query();		
			//query.setDbmanager();
			query.setReportname(report); 
			query.SetConditionmap(condition);
			query.initializeData();
			query.getResult();
			String buffer[]=query.getbuffer();
			System.out.println(buffer.length);
			
			if(buffer.length>0)
			{
				
					String splitheading [] = buffer[0].split("\t");
					int indeofprocess=-1;
					for(int i=0;i<splitheading.length;i++)
					{
						if(splitheading[i].equalsIgnoreCase(process))
						{
							indeofprocess = i;
							break;
						}
					}
					try {
						System.out.println( buffer[1].split("\t")[indeofprocess]);
						result = buffer[1].split("\t")[indeofprocess];
					} catch (ArrayIndexOutOfBoundsException e) {
						result = this.getFile();
					}
				
			}
		} catch (Exception e) {
			//e.printStackTrace();
			result = null;
		}
		
		return result;
	}
	
	public void setProcess(String process)
	{
		this.process = process;
	}
	
	public void setConditionHash(Hashtable<Object, Object> hash)
	{
		this.conditionhash = hash;
	}
	
	public void setDataHash(Hashtable<Object, Object> hash)
	{
		this.datahash = hash;
	}
	
	/**
	 * This method gets file content whether a file is to be accessed as an url or to be read as HTML 
	 * @param filename HTML Filename
	 * @return HTML data
	 */
	public String getFileContent(String filename)
	{
		String fileID = get.getId(filename);
		Hashtable<Object, Object> condition  = new Hashtable<Object, Object>();
		condition.put("mid", fileID);
		condition.put("pid",get.getId("pagetype"));
		condition.put("td","null");
		
		RecordSearch rec = new RecordSearch();
		rec.setConditionMap(condition);
		ResultSet rs = rec.getResultSet();
		String pagetype = "static";
		
		try {
			while(rs.next())
			{
				pagetype =  get.getItem(rs.getString("PV"));
				
				if(pagetype.equalsIgnoreCase("0") || pagetype.equalsIgnoreCase("no$"))
					pagetype = rs.getString("VT");
			}
			
			rs.close();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		String htmldata = null; 
		
		if(pagetype.equalsIgnoreCase("static"))
		{
			String path =  Input.LOCATION+filename+".html";
			File file = new File(path);
			byte[] html = null;
			
			try
	        {
	            html = new byte[new Long(file.length()).intValue()];
	            FileInputStream fis = new  FileInputStream(file);           
	            fis.read(html);
	        }
	        catch(FileNotFoundException e) {
	            html = path.getBytes();
	        }
	        catch (IOException e) {
				e.printStackTrace();
			}
	        
	        htmldata  = new String(html);
		}
		else
		{
			String property = null,value = null;
			
			try
			{
				condition = new Hashtable<Object, Object>();
				condition.put("name", fileID);
								
				rec.setConditionMap(condition);
				rs = rec.getResultSet();
				
				while(rs.next())
				{
					property = get.getItem((String)rs.getString("PID"));
					value = get.getItem(rs.getString("PV"));
					
					if(value.equalsIgnoreCase("no$"))
						value = rs.getString("VT");
					
					condition.put(property, value);
				}
			}
			catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			WebReportGenerator web = new WebReportGenerator(get.getId(filename), condition, ".html");
			htmldata = web.getData();
		}
        
        return htmldata;
	}
	
	/**
	 * This method returns the path of a static html page
	 * @return path of HTML page
	 */
	public String getFile()
	{
		String path = null, filename = null, result = null;
		RandomAccessFile raf = null;
		boolean GetDefault = false;
		
		try
		{
			try 
			{
				path = Input.LOCATION+this.page+".html";;
				raf = new RandomAccessFile(path,"r");
				filename = this.page+".html";
			}
			catch (FileNotFoundException e)
			{
				try
				{
					path = Input.LOCATION+CapitalChar.makeFirstCharCapital(page)+".html";
					raf = new RandomAccessFile(path,"r");
					filename = CapitalChar.makeFirstCharCapital(page)+".html";
				}
				catch (FileNotFoundException e3) 
				{
					WebReportGenerator web = new WebReportGenerator(this.pageID,datahash, ".html");
					web.getData();
					
					try 
					{
						path = Input.LOCATION+this.page+".html";;
						raf = new RandomAccessFile(path,"r");
						filename = this.page+".html";
					}
					catch (FileNotFoundException e1)
					{
						GetDefault = true;
					}
				}				
			}
			
			if(GetDefault)
			{
				try
				{
					path = Input.LOCATION+master+".html";
					raf = new RandomAccessFile(path,"r");
					filename = master+".html";
				}
				catch (FileNotFoundException e2) 
				{
					try
					{						
						path = Input.LOCATION+CapitalChar.makeFirstCharCapital(master)+".html";
						raf = new RandomAccessFile(path,"r");
						filename = CapitalChar.makeFirstCharCapital(master)+".html";
					}
					catch (FileNotFoundException e3) 
					{	
						try 
						{
							path = Input.LOCATION+this.masterID+".html";
							raf = new RandomAccessFile(path,"r");
							filename = this.masterID+".html";
						}
						catch (FileNotFoundException e) 
						{
							// TODO Auto-generated catch block
							//e.printStackTrace();
							System.out.println("Sorry No File Found");
							return null;
						}
						
					}
				}
			}
			
			result = filename;		
			return result;
		}
		catch (NullPointerException e) {
			e.printStackTrace();
			return null;
		}
		finally {
			rs = null;	
			raf = null;
		}
	}
	
	/**
	 * This method gets filename to be accessed without extension
	 * @return Filename
	 */
	public String getFileName()
	{
		String filename = null, result = null;
		RandomAccessFile raf = null;
		
		boolean GetDefault = true, breakFor = true;
		
		try
		{
			if(!this.masterID.equalsIgnoreCase(Input.TYPE))
			{
				rs  = DBManager.getSelect("SELECT * FROM property_details where mid = (select pv from property_details where mid="+get.getId(username)+" and pid="+get.getId("webpage")+") and pid="+this.masterID+" and td is null");
			
				while(rs.next())		
				{
					String pid = rs.getString("PID");
					String pv = rs.getString("PV");
					
					try 
					{
						raf = new RandomAccessFile(Input.LOCATION+get.getItem(pv)+".html","r");
						filename = get.getItem(pv);
						GetDefault = false;
					}
					catch (FileNotFoundException e)
					{
						// TODO Auto-generated catch block
						//e.printStackTrace();
						try 
						{
							raf = new RandomAccessFile(Input.LOCATION+this.pageID+".html","r");
							filename = this.pageID;
							GetDefault = false;
						}
						catch (FileNotFoundException e1) 
						{
							// TODO Auto-generated catch block
							//e1.printStackTrace();
							try 
							{
								raf = new RandomAccessFile(Input.LOCATION+page+".html","r");
								filename = this.page;
								GetDefault = false;
							}
							catch (FileNotFoundException e2) 
							{
								try 
								{
									raf = new RandomAccessFile(Input.LOCATION+CapitalChar.makeFirstCharCapital(page)+".html","r");
									filename = CapitalChar.makeFirstCharCapital(page);
									GetDefault = false;
								}
								catch (FileNotFoundException e3) 
								{
									e3.printStackTrace();
									GetDefault = true;
								}
							}
						}
					}
					
					break;
				}
			}
			else
			{
				GetDefault = true;
			}
			
			if(GetDefault)
			{
				try 
				{
					raf = new RandomAccessFile(Input.LOCATION+CapitalChar.makeFirstCharCapital(page)+".html","r");
					filename = CapitalChar.makeFirstCharCapital(page);
				}
				catch (FileNotFoundException e2) 
				{
					try 
					{
						raf = new RandomAccessFile(Input.LOCATION+page+".html","r");
						filename = page;
					}
					catch (FileNotFoundException e3) 
					{
						e3.printStackTrace();
					}
				}
				//break;
			}
			
			result = filename;		
			return result;
		}
		catch (SQLException e) 
		{
			e.printStackTrace();
			return null;
		}
		catch (NullPointerException e) 
		{
			e.printStackTrace();
			return null;
		}
		finally
		{
			rs = null;	
			raf = null;
		}
	}
	
	public static void main(String[] args)
	{
		RequestHandler requhand = new RequestHandler();
		
		Hashtable<Object, Object> hash = new Hashtable<Object, Object>();
		
		hash.put("process", "update");
		hash.put("objectname", "NIRMA DET SOAP");		
		hash.put("mastername","NIRMA DET SOAP");
		
		requhand.setUsername("systemuser");
		requhand.setRequestPage("item_update");
		requhand.setMaster("NIRMA DET SOAP");
		requhand.setDataHash(hash);
		requhand.setProcess("view");
		
		if(requhand.isUrl())
		{
			System.out.println("http://" +Input.URL+ requhand.getFile());
		}
		else
		{
			System.out.println(requhand.getHtml());
		}
		
		//String filename = requhand.getFileName();
		//System.out.println(requhand.getFileContent(filename));		
		//System.out.println(requhand.getFilePath());
	}
}
